package com.dswz.service.impl;

import com.dswz.service.SessionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Service("sessionService")
public class SessionServiceImpl implements SessionService {
	@Autowired
	JedisPool pool;
	private Integer exp = Integer.valueOf(30);

	public void setExp(Integer exp) {
		this.exp = exp;
	}

	public void setAttribute(String key, String type, String value) throws Exception {
		Jedis jedis = null;
		try {
			jedis = this.pool.getResource();
			jedis.set(key + ":" + type, value);
		} catch (Exception e) {
			throw e;
		} 
	}

	public void setAttribute2(String key, String type, String value) throws Exception {
		Jedis jedis = null;
		try {
			jedis = this.pool.getResource();
			jedis.set(key + ":" + type, value);
			jedis.expire(key + ":" + type, 60 * this.exp.intValue());
		} catch (Exception e) {
			throw e;
		} 
	}

	public void setAttribute(String key, String value) throws Exception {
		Jedis jedis = null;
		try {
			jedis = this.pool.getResource();
			jedis.set(key, value);
		} catch (Exception e) {
			throw e;
		} finally {
			if (jedis != null) {
				this.pool.returnResource(jedis);
			}
		}
		if (jedis != null) {
			this.pool.returnResource(jedis);
		}
	}

	public String getAttibute(String key, String type) throws Exception {
		Jedis jedis = null;
		try {
			jedis = this.pool.getResource();
			String username = jedis.get(key + ":" + type);
			if (StringUtils.isNotEmpty(username)) {
				jedis.expire(key + ":" + type, 60 * this.exp.intValue());
				return username;
			}
		} catch (Exception e) {
			throw e;
		} finally {
			if (jedis != null) {
				this.pool.returnResource(jedis);
			}
		}
		if (jedis != null) {
			this.pool.returnResource(jedis);
		}

		return null;
	}

	public String getAttribute(String key) throws Exception {
		Jedis jedis = null;
		try {
			jedis = this.pool.getResource();
			String result = jedis.get(key);
			if (StringUtils.isNotEmpty(result)) {
				return result;
			}
		} catch (Exception e) {
			throw e;
		} finally {
			if (jedis != null) {
				this.pool.returnResource(jedis);
			}
		}
		if (jedis != null) {
			this.pool.returnResource(jedis);
		}

		return null;
	}

	public void logout(String key, String type) throws Exception {
		delAttribute(key + ":" + type);
	}

	public void delAttribute(String key) throws Exception {
		Jedis jedis = null;
		try {
			jedis = this.pool.getResource();
			jedis.del(key);
		} catch (Exception e) {
			throw e;
		} finally {
			if (jedis != null) {
				this.pool.returnResource(jedis);
			}
		}
		if (jedis != null) {
			this.pool.returnResource(jedis);
		}
	}

	public Long increment(String id) throws Exception {
		return null;
	}

}
